var expressJwt = require("express-jwt");
// var bodyParser = require("body-parser");
var express = require("express");
var http = require("http");
// var debug = require("debug")("mall:server");
var path = require("path");
// var logger = require("morgan");
// var cookieParse = require("cookie-parser");
var app = express();

app.use((req, res, next) => {
  //设置请求头
  res.set({
    // "Access-Control-Allow-Origin": "*",
    // "Access-Control-Allow-Credentials": true,
    // "Access-Control-Max-Age": 1728000,
    "Access-Control-Allow-Origin": req.headers.origin || "*",
    "Access-Control-Allow-Headers":
      "X-Requested-With,Content-Type,Authorization",
    "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
    // "Content-Type": "application/html; charset=utf-8",
  });
  req.method === "OPTIONS" ? res.status(204).end() : next();
});

/**
 * 配置express使框架能够支持访问静态页面
 */
// 1、告诉express框架模板文件所在的位置
app.set("views", path.join(__dirname, "views"));
// 2、告诉express框架模板后缀是什么
app.set("view engine", "art");
// 3、当渲染后缀为art模板时，所使用的模板引擎是什么
app.engine("art", require("express-art-template"));

// app.use(logger("dev"));

app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);
// app.use(bodyParser.json());
// app.use(
//   bodyParser.urlencoded({
//     extended: true,
//   })
// );

// app.use(cookieParse());

// 在入口文件中设置托管   静态文件托管
app.use("/uploads", express.static(__dirname + "/uploads"));
// app.use(express.static(__dirname + "uploads"));
app.use(express.static(path.join(__dirname, "public")));

// ***************************************
var vertoken = require("./config/token");
// 解析token获取用户信息
app.use(function (req, res, next) {
  var token = req.headers["authorization"];
  if (token == undefined) {
    return next();
  } else {
    vertoken
      .verToken(token)
      .then((data) => {
        req.data = data;
        return next();
      })
      .catch((error) => {
        return next();
      });
  }
});
// 使用中间件验证token合法性
//验证token是否过期并规定哪些路由不用验证
//app.use(
  //expressJwt({
   // secret: vertoken.signkey,
   // algorithms: ["HS256"],
//  }).unless({
  //  path: ["/api/admin/login", "/api/users/login"], //除了这个地址，其他的URL都需要验证
 // })
// );
//当token失效返回提示信息
app.use(function (err, req, res, next) {
  if (err.status == 401) {
    return res.status(401).send("token失效");
  }
});

// ***************************************
app.use(function (req, res, next) {
  const proxy = req.query.proxy;
  if (proxy) {
    req.header.cookie = req.header.cookie + `__proxy__${proxy}`;
  }
  next();
});

// ********************************************************************************
let index = require("./routes/index");
let test = require("./routes/test");
let admin = require("./routes/admin");
let front = require("./routes/front");
let users = require("./routes/users");

app.use("/api", index);
app.use("/api/test", test);
app.use("/api/admin", admin);
app.use("/api/users", users);
app.use("/api/front", front);
// ********************************************************************************

const port = process.env.PORT || 3000;
// 启动Http服务
let server = http.createServer(app).listen(port, () => {
  console.log(`server running @http://localhost:${port}`);
});

// 处理401错误（要求身份验证）
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.status(401).json({
      status: false,
      msg: err,
    });
  }
});

// 处理404错误 （服务器找不到网页）
app.use(function (req, res, next) {
  var err = new Error("Not Found");
  err.status = 404;
  // next("没有找到页面");
  next(err);
});

// 500处理 （服务器遇到错误）
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
